const Koa = require('koa');
const KoaRouter = require('koa-router');
const koaBody = require('koa-body');
const jsonwebtoken = require('jsonwebtoken');
const koaStaticCache = require('koa-static-cache');

const server = new Koa();
const key = 'kkb';

server.use(koaStaticCache({
    prefix: '/public',
    dir: './public',
    gzip: true,
    dynamic: true
}));

const router = new KoaRouter();

router.post('/login', async (ctx, next) => {

    // ctx.cookies.set('uid', 1);
    const token = jsonwebtoken.sign({ uid: 1 }, key);
    // console.log(token);

    ctx.set('Authorization', token);

    ctx.body = '登录成功';
});

router.get('/dahai', async (ctx, next) => {

    let token = ctx.get('authorization');
    let user = null;
    try {
        user = jsonwebtoken.verify(token, key);
        console.log(user);
        ctx.body = '大海现在在峡谷被虐！';
    } catch (e) {
        ctx.body = '不能看';
    }

    // if (ctx.cookies.get('uid')) {
    //     ctx.body = '大海现在在峡谷被虐！';
    // } else {
    //     // ctx.throw(401, '不能看');
    //     ctx.body = '不能看';
    // }
});

server.use(router.routes());

server.listen(8888);
